﻿using UnityEngine;
using System.Collections;

public class ButtonLine : MonoBehaviour {

	public Vector3[] points = new Vector3[4];

	public GameObject button;

	public GameObject mainCamera;

	public float distance;

	[HideInInspector] public GameObject[] obstacles;
	[HideInInspector] public int a;
	[HideInInspector] public int b;
	[HideInInspector] public GameObject target;

	public bool lineOn;

	public float lane;
	public float zAxisOut;
	public float waitTime;

	public LineRenderer line;

	public Color c1 = Color.black;
	public Color c2 = Color.white;

	private bool coStart;


	// Use this for initialization
	void Start () {

		line.enabled=true;
	
	}
	
	// Update is called once per frame
	void Update () {

		distance = Vector3.Distance (button.transform.position, mainCamera.transform.position);

		points[0] = new Vector3(button.transform.position.x,button.transform.position.y,button.transform.position.z-zAxisOut);
		points[1] = new Vector3(button.transform.position.x,lane,button.transform.position.z-zAxisOut);

		if (lineOn==true)
		{
			StopCoroutine("loopPoints");
			line.SetColors(c2, c2);
			points[2] = new Vector3(target.transform.position.x,lane,target.transform.position.z-zAxisOut);
			points[3] = new Vector3(target.transform.position.x,target.transform.position.y,target.transform.position.z-zAxisOut);

		}
		else
		{
			line.SetColors(c1, c1);
		}

			line.SetWidth(0.2F, 0.2F);

			line.SetPosition(0,points[0]);
			line.SetPosition(1,points[1]);
			line.SetPosition(2,points[2]);
			line.SetPosition(3,points[3]);

		if(b == obstacles.Length)
		{
			b=0;
		}

		if(coStart==false)
		{
				StartCoroutine("loopPoints");
				coStart =true;
		}
	
	}

	IEnumerator loopPoints ()
	{
		do
		{
			Debug.Log(b);
			points[2] = new Vector3(obstacles[b].transform.position.x,lane,obstacles[b].transform.position.z-zAxisOut);
			points[3] = new Vector3(obstacles[b].transform.position.x,obstacles[b].transform.position.y,obstacles[b].transform.position.z-zAxisOut);
			b++;
			yield return new WaitForSeconds(waitTime);

		}
		while(lineOn==false);
	}
}
